<?php

namespace app\admin\controller;

use app\admin\constants\AdminConstants;
use app\admin\model\Admin;
use app\common\controller\Backend;
use PhpParser\Node\Name;

/**
 * 门店信息管理
 */
class Store extends Backend
{
    /**
     * Store模型对象
     * @var object
     * @phpstan-var \app\admin\model\Store
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'admin_id', 'created_at', 'updated_at', 'external_id'];

    protected string|array $quickSearchField = ['id', 'name'];
    protected array $noNeedLogin = ['apiStores'];
    protected array $noNeedPermission = ['apiStores'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Store();
    }

    public function apiStores()
    {
        $api_token = $this->request->header('token') ?: $this->request->param('token', '');
        if ($api_token != AdminConstants::API_TOKEN) {
            $this->error('token错误');
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        // $where[] = Admin::getLoginAdminStores('id')['where']; //此列表显示登录用户有权查看的所有门店，不根据用户选择进行过滤
        $res = $this->model
            ->field('id,name')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        // 获取门店列表
        $storeList = $res->items();

        $this->success('', [
            'list'   => $storeList,
            'total'  => $res->total(), // 总数加1，因为添加了"全部门店"选项
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $where[] = Admin::getLoginAdminStores('id')['where']; //此列表显示登录用户有权查看的所有门店，不根据用户选择进行过滤
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        // 获取门店列表
        $storeList = $res->items();

        // // 在列表前面添加"全部门店"选项
        // if ($this->request->param('type') == 'select') {
        //     // 将"全部门店"选项插入到列表开头
        //     array_unshift($storeList, ['id' => 0, 'name' => '全部门店']);
        // }

        $this->success('', [
            'list'   => $storeList,
            'total'  => $res->total(), // 总数加1，因为添加了"全部门店"选项
            'remark' => get_route_remark(),
        ]);
    }
}
